#!/usr/bin/python


import urllib
import webbrowser
import sys
import re
import urllib2


GOAGENT = '127.0.1:8087'
WCHAMBER = '127.0.1:1998'

def getItemsFromURL( proxysetting, URL ):
	
	"""
	proxysetting : proxy setting
	URL: the rss feed url


	return a list of tuples (title, magnetLink)
	"""
	
	#directly read from URL
	#rssStr = urllib.urlopen(URL)

	rssStr = None
	if proxysetting == 'none':
		rssStr = urllib.urlopen(RSSURL)
		print 'not using proxy'

	else:
		print 'using proxy: ', proxysetting
		proxy = urllib2.ProxyHandler({'http': proxysetting})
		opener = urllib2.build_opener(proxy)
		urllib2.install_opener(opener)
		rssStr = urllib2.urlopen(URL)
	


	webpage = rssStr.read()

	titleP = re.compile(r'<title><!\[CDATA\[(.+)\]\]></title>')
	titleList = titleP.findall(webpage)

	
	linkP = re.compile(r'(magnet.+)</link>')
	linkList = linkP.findall(webpage)

	#tuple list
	collection = []

	count = 0

	#checking if the link is really for the title
	for i in range(0, len(titleList)):
		
		titleS = re.sub('&amp;', '&', titleList[i])
		linkS = re.sub('&amp;', '&', linkList[i])
		#&#039
		titleS = re.sub('&#039;', '\'', titleS)
		linkS = re.sub('&#039;', '\'', linkS)
		
		if titleList[i] in linkList[i]:
			count += 1
			collection.append((titleS, linkS))

		else:
			m = re.search(r'\w+', titleList[i])
			if m.group() in linkList[i]:
				
				collection.append((titleS, linkS))
				count+= 1

			#we have a problem, the link is not for the title
			else:
				print titleS
				print linkS

	if count == len(titleList):
		print 'its all good'

	return collection

def main():
	args = sys.argv[1:]
	getItemsFromURL(args[0])

if __name__ == '__main__':

	

	
	main()

